#include "msg_handler.h"


/**
 * Name:    core_upload_transport
 * Brief:   采集通道消息逐一分发到转发通道
 * Input:
 *  @pu:    消息源: 采集通道
 *  @msg:   消息:   网关内部消息
 * Output:  cfg_pu_t*
 */
static core_upload_transport(cfg_pu_t *pu, msg_t *msg)
{
    // 南向消息推送至北向
    cfg_pu_t *cur = g_cfg->g_coll_link;
    while(cur)
    {
        if( strcmp(cur->name,pu->name) == 0 && cur->enable)
        {
            switch(msg->type)
            {
                case MSG_TYPE_ALM_YX:
                    break;
                default:
                    log_err("core_msg","unsupport msg type:%d",msg->type);
                    return -1;
            }

            cfg_pu_t* north = g_cfg->g_trans_link;
            while(north)
            {
                // 忽略 初始化不成功的转发 
                if(north->enable)
                {
                    dlmodule_t* dlmodule = (dlmodule_t*)north->hanlder.dlmodule;
                    if(dlmodule->msg)dlmodule->msg(north,msg);
                }
                north = north->next;
            }
            return 0;
        }
    }
    return -1;
}

/**
 * Name:    core_upload_transport
 * Brief:   转发通道消息下发到指定的采集通道
 * Input:
 *  @pu:    消息源: 转发通道
 *  @msg:   消息:   网关内部消息
 * Output:  cfg_pu_t*
 */
static core_download_transport(cfg_pu_t *pu, msg_t *msg)
{
    // 北向消息推送至南向
    cfg_pu_t *trans = g_cfg->g_trans_link;
    while (trans)
    {
        if (strcmp(trans->name, pu->name) != 0)
        {
            trans = trans->next;
            continue;
        }

        cfg_pu_t *coll = g_cfg->g_coll_link;
        while (coll)
        {
            cfg_su_t *dev = coll->su;
            while (dev)
            {
                // 根据su查找到对应的pu，并将消息推送至节点
                if (strcmp(msg->su, dev->name) != 0)
                {
                    dev = dev->next;
                    continue;
                }
                dlmodule_t *dlmodule = (dlmodule_t *)coll->hanlder.dlmodule;
                if (NULL == dlmodule)
                {
                    return -1;
                }
                return dlmodule->msg(coll, msg);
            }
            coll = coll->next;
        }
        return -1;

    }
    return -1;
}

/**
 * Name:    core_msg_handler
 * Brief:   解析采集层配置
 * Input:
 *  @pu:    消息源: 通道
 *  @msg:   消息:   网关内部消息协议
 * Output:  cfg_pu_t*
 */
int core_msg_handler(cfg_pu_t *pu, msg_t *msg)
{
    if (0 == pu->type)  //0 消息源:采集通道
    {
        // 采集通道 -- > 转发通道 (上行)
        return core_upload_transport(pu, msg);
    }
    else                //1 消息源:转发通道
    {
        // 转发通道 -- > 采集通道 (下行)
        return core_download_transport(pu, msg);
    }
    return 0;
}